<template>
  <div class="snapped">
    <Header />
    <Notice />
    <!-- <Session :session-list="sessionList" /> -->
    <!-- <van-pull-refresh v-model="isLoading" @refresh="onRefresh"> -->
      <!-- :is-loading="isLoading" -->
      <Goods-limit
        ref="goodsRef"
        title-name="采购商品"
        :goods-list="formerOrderList"
        :is-finished="false"
        :description="descriptions"
        @confirm="onConfirm"
        @onReachBottom="onReachBottom"
      />
    <!-- @handleCheckbox="handleCheckbox" -->
    <!-- </van-pull-refresh> -->
    <back-top :is-buy="true" />
    <!-- <Tabbar v-if="formerOrderList && formerOrderList.length > 0" :amount="amount" :value="isAllSelect" @input="handleAllSelect" @onConfirm="onConfirm" /> -->
    <Skeleton v-if="isSkeletonShow" />
  </div>
</template>

<script>
import { getHomeCgData,getIsOpenCg } from '@/api/home'
import { verifyAddCartCg } from '@/api/cart'
import { getUserSign,getInfo } from '@/api/user'
import { getLeaderPhone } from '@/api/user'
import Header from './modules/Header'
import GoodsLimit from './modules/GoodsLimit.vue'

// import GoodsLimit from './modules/GoodsVantCard.vue'
import Tabbar from './modules/Tabbar.vue'
import Notice from './modules/Notice.vue'

// import Session from './modules/Session'
import Skeleton from './modules/Skeleton'
import { addShopCart } from '@/api/cart'
import { mapGetters } from 'vuex'
import Description from '../detail/modules/Description.vue'

export default {
  name: 'Snapped',
  components: {
    Header,
    Notice,
    // Goods,
    // Session,
    GoodsLimit,
    Tabbar,
    Skeleton
  },
  data() {
    return {
      mallConfig: {},
      bannerList: [],
      // sessionList: [],
      formerOrderList: [],
      amount: 0,
      isAllSelect: false,
      pageSize: 10,
      pageNum: 1,
      isLoading: false,
      isFinished: false,
      isSkeletonShow: true,
      checkCartOption: {},
      descriptions:'联系店长上架吧~',
      userInfo:{}
    }
  },
  watch: {
    formerOrderList(newval) {
      // let num = 0
      // newval.forEach(item => {
      //   if (item.checked) num += parseFloat(item.price) * item.number
      //   item.goodsPrice = item.goodsPrice * item.goodsCount
      // })
      // this.isAllSelect = newval.every(item => {
      //   return item.checked === true
      // })
      // this.amount = num * 100
    }
  },
  computed: {
    // ...mapGetters(['userInfo'])
  },
  async activated(){
    
  },
  async mounted() {
    this.isLoading = false
    const res = await getInfo()
    this.userInfo = res.map.info
    console.log(res)
    this.formerOrderList = []

    console.log(this.userInfo)
    if (this.userInfo.userLevel == 0) {
      const ress =await getLeaderPhone()
      this.$toast({
        message: `暂未开放，请与店长联系：${ress.map.phone}`,
        duration: 10000,
        position: 'center',
        icon: 'error'
      })
      setTimeout(() => {
        this.$router.push({ name: 'Home' })
      }, 10000)
      return
    }
    const list = await this.$store.dispatch('address/getList')
    if(list.length == 0){
      this.$router.push('/address')
    }
    this.getSign()
    const flag = await this.getIsOpenCgData()
    console.log(flag)
    if(flag){
      this.isLoading = false
      this.getHomeCgData()
    }else{
      this.formerOrderList = []
        this.isSkeletonShow = false
        // if (this.formerOrderList && this.formerOrderList.length <) {
        //
        // }
        this.$refs.goodsRef.checkedList = []
        this.isLoading = false
        this.descriptions='今日采购区暂停营业，请联系店长~'

      return this.$toast.fail('当前休仓中，请联系店长')
    }
  },
  methods: {
    async getIsOpenCgData(){
      const {map: {isOpen}} =await getIsOpenCg()
      return isOpen==0? false:true
    },
    getSign() {
      getUserSign().then((res) => {
        if (res.map.userSign === undefined || res.map.userSign.length === 0) {
          this.$dialog.confirm({
            title: '参与采购必须签署部分协议,是否现在去签署',
            cancelButtonText: '取消'
          }).then(res => {
            if (res === 'confirm') {
              this.$router.push({ name: 'Notice' })
            } else {
            }
          }).catch(res=>{
            console.log(res)
            this.$router.push('/home')
          })
        }
      })
    },
    async onConfirm(item) {
      console.log(item)
      const flag = await this.getIsOpenCgData()
      if(!flag){
        return this.$toast.fail('今日采购区暂停营业，请联系店长')
      }
      const {map:{message}} = await verifyAddCartCg()
      console.log(message)
      if(message){
        return this.$toast.fail(message)
      }
      const option = item
      if (!option || !option.id) {
        return
      }
      this.$dialog.confirm({title:'是否确定加入购物车？'}).then( (res)=>{
         addShopCart({ orderId: option.id }).then(res=>{
          this.$toast.success('采购成功')
          this.isLoading = true
          this.formerOrderList = []
          this.descriptions = '加载中'
          this.isFinished = false
          this.$store.dispatch('user/getCartGoodCount')
          
          this.getHomeCgData()
         })
      
      }).catch(res=>{
        return false
      })
      
    },
    handleCheckbox(index, flag) {
      console.log(index, flag)
      const goodsList = this.formerOrderList
      // goodsList.forEach((item, idx) => {
      //   if (idx === index) {
      //     goodsList[idx].checked = !goodsList[idx].checked
      //   } else {
      //     goodsList[idx].checked = false
      //   }
      // })
      if (flag) {
        this.checkCartOption = goodsList[index]
        this.amount = goodsList[index].goodsPrice * 100
      } else {
        this.amount = 0
        this.checkCartOption = {}
      }
    },
    getHomeCgData() {
      debugger
      // this.isLoading = true
      // this.$toast.loading('火爆抢购中')
      getHomeCgData({
        pageSize: this.pageSize,
        pageNum: this.pageNum
      }).then(res => {
        const { map } = res
        console.log(map.message)
        if(map.message!==undefined){
          this.formerOrderList=[]
          this.isSkeletonShow = false
          this.isLoading = false
          this.descriptions= map.message
          if(this.formerOrderList.length==0){
            this.descriptions = map.message
          }

          if(!localStorage.getItem('fresh')){
            localStorage.setItem('fresh',1)
            location.reload(true)
          }else{
            return this.$toast.fail(map.message)
          }
        }
        console.log('直接打印数据',res)
        map.formerOrderList.forEach(item=>{
          item.goodsImg +='?imageView2/1/w/600/h/600'

        })
        this.formerOrderList = [...this.formerOrderList, ...map.formerOrderList]
        this.isSkeletonShow = false
        console.log('直接打印数据',this.formerOrderList)
        debugger
        this.descriptions= null
        if(this.formerOrderList.length==0){
          this.descriptions ="联系店长上架吧~"
        }
        this.$refs.goodsRef.checkedList = []

        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
    },
    handleAllSelect(value) {
      this.formerOrderList.filter(item => {
        return item.maxNum >= item.number
      })
      this.formerOrderList.forEach((item, i) => {
        this.$set(this.list, i, item)
      })
    },
    // reach-bottom
    onReachBottom() {
      this.isLoading = true
      if (this.isLoading) {
        this.pageNum += 1
        this.getHomeCgData()
      }
    }
  }
}
</script>

<style>
:deep(.back-top){
  position: fixed;
  bottom: 180px;
}
</style>

<style lang="scss" scoped>
.home {
  background: #f5f5f5;
  min-height: 100vh;
  .logo {
    display: block;
    width: 200px;
    margin: 0 auto;
    padding-top: 40px;
  }
  .menu__right {
    width: 50px;
  }
}
</style>
